﻿var client;
var opened = false;
this.isHost = false;
this.isStarted = false;
this.players = new Array();
this.playerName = "";

function connect() {
	/*
	 * This function is executed when player want to connect to server
	 */
	var location = document.getElementById('location').value;
	document.getElementById('connection').style.display = 'none';
	document.getElementById('connecting').style.display = 'block';
	client = new WebSocket("ws://" + location);

	client.onopen = function(e) {
		/*
		 * If player is connected
		 */
		opened = true;
		document.getElementById('connecting').style.display = 'none';
		document.getElementById('gaming').style.display = 'block';
		document.getElementById('border').style.display = 'block';

	};

	client.onclose = function(e) {
		/*
		 * Occured when server is close
		 */
		document.getElementById('connection').style.display = 'block';
		document.getElementById('connecting').style.display = 'none';
		document.getElementById('gaming').style.display = 'none';
		document.getElementById('game').style.display = 'none';
		document.getElementById('gameStart').style.display = 'none';
		document.getElementById('ready').style.display = 'none';
		document.getElementById('border').style.display = 'none';
		if (opened) {
			alert("Connection closed.");
		} else {
			alert("Error: failed to connect.");
		}
		opened = false;
	};

	client.onmessage = function(e) {
		var tab = e.data.split("\n");
		readMessage(tab);
	};

	client.onerroe = function(e) {
		alert("Error: " + e.data);
	};
};
function sendScore(t) {
	/*
	 * This function send message to server which team scored a goal
	 */
	client.send("PLAYER\n" + players[0] + "\nTEAM SCORE\n" + t);
	previousBallPosition['x'] = 400;
	previousBallPosition['y'] = 210;
	ballPosition['x'] = 400;
	ballPosition['y'] = 210;
	// Stop ball move for 3 sec and set ball on the center
	clearInterval(intervalHandler);
	intervalHandler = "";
	setTimeout("start()", 3000);
	sendBallPosToServer();
}
function hostGame() {
	client
			.send("PLAYER\n" + document.getElementById('playerName').value
					+ ":" + this.CID + "\nHOST\n"
					+ document.getElementById('gameName').value);
	this.isHost = true;
}

function gameReady() {
	/*
	 * Prepare board if game is ready to play
	 */
	document.getElementById('game').style.display = 'block';
	document.getElementById('connecting').style.display = 'none';
	document.getElementById('gaming').style.display = 'none';
	document.getElementById('gameStart').style.display = 'block';
}
function connectGame() {
	/*
	 * This function send info to server that new player joined to game
	 */
	var sel = document.getElementById('games');
	for ( var j = 0; j < sel.length; ++j) {
		if (sel.options[j].selected) {
			client.send("PLAYER\n"
					+ document.getElementById('playerName').value + ":"
					+ this.CID + "\nJOIN\n" + sel.options[j].value);
		}
	}
	document.getElementById('game').style.display = 'block';
	document.getElementById('connecting').style.display = 'none';
	document.getElementById('gaming').style.display = 'none';
	document.getElementById('clientReady').style.display = 'block';
};

function refreshList() {
	client.send("GAMES");
};
function iAmReady() {
	// Non host client says that his state is ready to play
	client.send("PLAYER\n" + playerName + ":" + CID + "\nSTATE\nREADY");
	document.getElementById('ready').disabled = true;
};
function gameStart() {
	// Host start the game
	if (isHost)
		client.send("PLAYER\n" + playerName + ":" + CID + "\nSTATE\nSTARTED");
}
function clearList() {
	var sel = document.getElementById('games');
	for ( var j = sel.length - 1; j >= 0; --j) {
		sel.remove(j);
	}
};
function positionUp() {
	client.send("PLAYER\n" + playerName + ":" + CID + "\nPPOS\n"
			+ playerPos['x'] + ":" + playerPos['y'] + "\nPMOVE\nUP");
}

function positionDown() {
	client.send("PLAYER\n" + playerName + ":" + CID + "\nPPOS\n"
			+ playerPos['x'] + ":" + playerPos['y'] + "\nPMOVE\nDOWN");
}
function addToList(el) {
	// Add game to game list
	var newOpt = document.createElement('option');
	newOpt.text = el;
	newOpt.value = el;
	var sel = document.getElementById('games');
	try {
		sel.add(newOpt, null); // Standards compliant.
	} catch (ex) {
		sel.add(newOpt); // For my love IE.
	}
};
function readMessage(msg) {
	/*
	 * This function is responsible for parsing a messages from server
	 */
	switch (msg[0].toUpperCase()) {
	case 'GAMES':
		clearList();
		updateList(msg[1].split(":"));
		break;
	case 'WAIT':
		break;
	case 'ERROR':
		alert(msg[1]);
		break;
	case 'BPOS':
		var str = msg[1].split(":");
		previousBallPosition['x'] = ballPosition['x'];
		previousBallPosition['y'] = ballPosition['y'];
		ballPosition['x'] = parseInt(str[0]);
		ballPosition['y'] = parseInt(str[1]);
		if (!isHost) {
			drawBall();
		}
		break;
	case 'STATE':
		if (msg[1] == 'READY' & !isStarted)
			document.getElementById('start').disabled = false;

		if (msg[1] == 'STARTED' && isHost) {
			client.send("PLAYER\n" + playerName + ":" + CID + "\nBPOS\n"
					+ "300" + ":" + "200" + "\nBMOVE\n" + "1:1");
			isStarted = true;
			start();
			document.getElementById('start').disabled = true;
		} else if (msg[1] == 'STARTED')
			isStarted = true;
		break;
	case 'SCORE':
		document.getElementById('game').innerText = msg[1];
		document.getElementById('game').textContent = msg[1];
		break;
	default:
		break;

	}
	if (msg.length >= 3) {
		switch (msg[2].toUpperCase()) {
		case 'CID':
			this.CID = msg[3];
			break;
		case 'PPOS':
			var playerNr = players.indexOf(msg[1]) + 1;
			var str = msg[3].split(":");
			changePlayerPos(str[0], str[1], playerNr);
			drawOpponentPaddle(playerNr);
			break;
		case 'JOIN':
			if (msg.length > 14) {
				addPlayer(msg[5]);
				addPlayer(msg[9]);
				addPlayer(msg[13]);
				addPlayer(msg[1]);
				setPlayerName(msg[1]);
				setPlayerPos(players.length);
				for ( var int = players.length; int >= 1; int--) {
					drawOpponentPaddle(int);
				}

			} else if (msg.length > 10) {
				addPlayer(msg[5]);
				addPlayer(msg[9]);
				addPlayer(msg[1]);
				setPlayerPos(players.length);
				setPlayerName(msg[1]);
				for ( var int = players.length; int >= 1; int--) {
					drawOpponentPaddle(int);
				}
			} else if (msg.length > 6) {
				addPlayer(msg[5]);
				addPlayer(msg[1]);
				setPlayerPos(players.length);
				setPlayerName(msg[1]);
				for ( var int = players.length; int >= 1; int--) {
					drawOpponentPaddle(int);
				}
			} else {
				addPlayer(msg[1]);
				setPlayerPos(players.length);
				setPlayerName(msg[1]);
				gameReady();

			}
			break;
		case 'JOINED':
			addPlayer(msg[1]);
			drawOpponentPaddle(players.length);
			break;
		default:
			break;
		}
	}

};
function setPlayerName(m) {
	var arr = m.split(":");
	playerName = arr[0];
}
function addPlayer(p) {
	/*
	 * This function add players to list of players. If new player join to game
	 * it add him and if other players are in game it allso adds them
	 * 
	 */
	var newOpt = document.createElement('option');
	newOpt.text = p;
	newOpt.value = p;
	players.push(p);
	var sel = document.getElementById('playersList');
	try {
		sel.add(newOpt, null); // Standards compliant.
	} catch (ex) {
		sel.add(newOpt); // For my love IE.
	}
}
function sendBallPosToServer() {
	if (isHost)
		client.send("PLAYER\n" + playerName + ":" + CID + "\nBPOS\n"
				+ ballPosition['x'] + ":" + ballPosition['y'] + "\nBMOVE\n"
				+ "1:1");
}
function updateList(options) {
	for ( var j = 0; j < options.length; ++j) {
		addToList(options[j]);
	}
};